package com.ftg.learn.util;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author 布衣
 */
public class SmsUtil {

    /**
     *
     * @param phone
     * @param code
     * @return
     */
    public static String sendSms(String phone,String code){
        return sendSms("LTAI5tPZW7rvqbSYp49GsziT","oMaUS5Wv1uHvXjZpKnYZRaaz0QBcYp","cn-qingdao","dysmsapi.aliyuncs.com",phone,code,"阿里云短信测试","SMS_154950909");
    }

    /**
     * 发送短信
     * @param accessKeyId
     * @param accessKeySecret
     * @param region
     * @param endpoint
     * @param phone
     * @param code
     * @param signName
     * @param templateCode
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static String sendSms(String accessKeyId, String accessKeySecret, String region,
                                 String endpoint, String phone, String code, String signName, String templateCode) {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                //"LTAI5tPZW7rvqbSYp49GsziT"
                .accessKeySecret(accessKeySecret)
                //"oMaUS5Wv1uHvXjZpKnYZRaaz0QBcYp"
                .build());

        try (
                AsyncClient client = AsyncClient.builder()
                        .region(region) // Region ID "cn-qingdao"
                        .credentialsProvider(provider)
                        .overrideConfiguration(
                                ClientOverrideConfiguration.create()
                                        //"dysmsapi.aliyuncs.com"
                                        .setEndpointOverride(endpoint)
                        )
                        .build();
        ) {

            //发送功能参数
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .phoneNumbers(phone)
                    .signName(signName)//"阿里云短信测试"
                    .templateCode(templateCode) //"SMS_154950909"
                    .templateParam("{\"code\":\"" + code + "\"}")
                    .build();

            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();
            return new Gson().toJson(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{code:50019,msg:\"sms发送失败\"}";
    }

}

